package com.ht.managermentserver.handler;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ht.managermentserver.entity.SysUser;
import com.ht.managermentserver.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/** @author czy */
@Component
@Slf4j
public class MybatisPlusHandler implements MetaObjectHandler {

  @Autowired HttpServletRequest httpServletRequest;

  @Override
  public void insertFill(final MetaObject metaObject) {
    this.strictInsertFill(metaObject, "createDate", LocalDateTime.class, LocalDateTime.now());
    this.strictInsertFill(metaObject, "createId", Long.class, getSystemUserLogin().getId());

    this.strictInsertFill(metaObject, "version", Integer.class, 1);
    this.strictInsertFill(metaObject, "deleted", Boolean.class, false);
    this.strictInsertFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
    this.strictInsertFill(metaObject, "updateId", Long.class, getSystemUserLogin().getId());
  }

  @Override
  public void updateFill(final MetaObject metaObject) {
    this.strictInsertFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
    this.strictInsertFill(metaObject, "updateId", Long.class, getSystemUserLogin().getId());
  }

  private SysUser getSystemUserLogin() {
    final SysUser user = new SysUser();
    try {

      final String authorization = httpServletRequest.getHeader("authorization");
      if (StringUtils.isEmpty(authorization) && !JwtTokenUtil.verifyJwtToken(authorization)) {
        user.setId(0L);
        return user;
      }

      final Long userid = JwtTokenUtil.getUserId(authorization);

      user.setId(userid);
      return user;
    } catch (final Exception ex) {

      log.error(ex.getMessage(), ex);

      return user.setId(0L);
    }
  }
}
